package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ydkj.a37e_mall.Classes.Model.Request.AllProductReq;
import com.ydkj.a37e_mall.Classes.Model.Response.AllProductResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by Administrator on 2017/3/3.
 */

public class AllProduct extends BaseActivity {
    private Activity mActivity;
    private TextView tv_title;
    private PullToRefreshGridView gv_all_product;
    private AllproductAdapter allProductGridviewAdapter;
    private List<AllProductResp.ResultEntity.DataEntity> all_productList;
    private String id;
    private String titlename;
    private int page;
    private static final int LOAD = 0;// 加载
    private static final int REFRESH = 1;// 刷新
    private static final int MORE = 2;// 更多
    private ImageView img_back;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_product_shelves);

        mActivity = this;
        init();
        GetAllProduct(REFRESH);
//        initWindow();//沉浸式状态栏
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.e50011), 0);
    }


    private void init() {
        tv_title = (TextView) mActivity.findViewById(R.id.tv_title);

        if (this.getIntent().getExtras() != null) {
            id = this.getIntent().getExtras().getString("id");
            titlename = this.getIntent().getExtras().getString("titlename");
            tv_title.setText(titlename);

            Log.e("ssss", "全部商品id==" + id);
            Log.e("ssss", "全部商品titlename==" + titlename);
        }

        img_back = (ImageView) mActivity.findViewById(R.id.img_back);

        gv_all_product = (PullToRefreshGridView) mActivity.findViewById(R.id.gv_new_product);
        all_productList = new ArrayList<>();
        allProductGridviewAdapter = new AllproductAdapter(all_productList);
        gv_all_product.setAdapter(allProductGridviewAdapter);

        gv_all_product.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                String label = DateUtils.formatDateTime(mActivity.getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                // Do work to refresh the list here.
                GetAllProduct(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                String label = DateUtils.formatDateTime(mActivity.getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                // Do work to refresh the list here.
                GetAllProduct(MORE);
            }
        });

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    //全部商品 Adapter
    private class AllproductAdapter extends BaseAdapter {
        private List<AllProductResp.ResultEntity.DataEntity> all_productList;

        public AllproductAdapter(List<AllProductResp.ResultEntity.DataEntity> info) {
            if (info == null) {
                info = new ArrayList<AllProductResp.ResultEntity.DataEntity>();
            }
            all_productList = info;
        }

        @Override
        public int getCount() {
            return all_productList.size();
        }

        @Override
        public AllProductResp.ResultEntity.DataEntity getItem(int position) {
            return all_productList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(R.layout.allproduct_gridview, null);
                vh = new ViewHolder();
                vh.img_all_product = (ImageView) convertView.findViewById(R.id.img_all_product);
                vh.tv_search_name= (TextView) convertView.findViewById(R.id.tv_search_name);
                vh.tv_search_describe = (TextView) convertView.findViewById(R.id.tv_search_describe);
                vh.tv_search_price = (TextView) convertView.findViewById(R.id.tv_search_price);
                vh.tv_search_original_price = (TextView) convertView.findViewById(R.id.tv_search_original_price);
                vh.tv_search_payment_number = (TextView) convertView.findViewById(R.id.tv_search_payment_number);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            convertView.setClickable(true);


            vh.tv_search_name.setText(getItem(position).getName());
            vh.tv_search_describe.setText(getItem(position).getDescription());
            vh.tv_search_price.setText("￥ "+getItem(position).getPrice());
            vh.tv_search_payment_number.setText(getItem(position).getSales() + "人付款");
            ImageLoader.getInstance().displayImage(getItem(position).getList_thumb(), vh.img_all_product, displayImageOptions);
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mActivity, ProductDetails.class);
                    intent.putExtra("id", getItem(position).getId() + "");
                    startActivity(intent);
                }
            });

            return convertView;
        }

        class ViewHolder {
            private ImageView img_all_product;
            private TextView tv_search_name,tv_search_describe,tv_search_price,tv_search_original_price,tv_search_payment_number;
        }
    }

    //获取  (全部商品)
    private void GetAllProduct(final int type) {
        AllProductReq req = new AllProductReq();
        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = (all_productList.size() / 10 + 1);
        }
        req.setType("0");
        req.setPage(page + "");
        req.setPage_size("10");
        req.setSort("id");
        req.setOrder("asc");


        RequestParams params = new RequestParams();
        params.put("secret", req.getSecret());

        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                gv_all_product.onRefreshComplete();
                Log.e("ssss", "获取全部商品");
//                Log.e("ssss", "GetAllProductjson1111==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errno.equals("000")) {
                    AllProductResp resp = GsonImpl.get().toObject(response.toString(), AllProductResp.class);

                    if (type == LOAD || type == REFRESH) {
                        all_productList.clear();
                        all_productList.addAll(resp.getResult().getData());
                    } else {
                        all_productList.addAll(resp.getResult().getData());
                    }
                    if (all_productList.size() % 10 > 0) {
                        gv_all_product.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        gv_all_product.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    allProductGridviewAdapter.notifyDataSetChanged();

                } else {
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CommonUtil.showToast(mActivity, "网络连接失败");
                gv_all_product.onRefreshComplete();
            }
        });
    }
}
